package cn.itcast.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 自定义全局过滤器
 */
@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {
    /**
     * 需求 ：请求参数中带有token 内容，就放行，否则提示未授权
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("自定义全局过滤器-执行-----------");
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取参数
        MultiValueMap<String, String> valueMap = request.getQueryParams();
        List<String> valList = valueMap.get("token");
        if (CollectionUtils.isEmpty(valList)){
            //异常情况，没有token参数
            //获取响应对象
            ServerHttpResponse response = exchange.getResponse();
            //返回响应码
            response.setStatusCode(HttpStatus.FORBIDDEN);
            //完场响应
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
